package com.cjst.controller.api.login;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.cjst.controller.base.BaseController;
import com.cjst.dto.SysDictDto;
import com.cjst.pojo.base.Article;
import com.cjst.pojo.sys.FileInfo;
import com.cjst.pojo.sys.SysOffice;
import com.cjst.pojo.sys.SysUser;
import com.cjst.sdp.util.MenuNode;
import com.cjst.sdp.util.ShiroKit;
import com.cjst.service.base.ArticleService;
import com.cjst.service.redis.RedisService;
import com.cjst.service.sys.FileInfoService;
import com.cjst.service.sys.SysDictService;
import com.cjst.service.sys.SysMenuService;
import com.cjst.service.sys.SysOfficeService;
import com.cjst.service.sys.SysUserService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;
import com.cjst.thirdparty.jpush.JPushDeviceUtil;
import com.cjst.util.ErroResult;
import com.cjst.util.UserPrincipalUtil;
import com.cjst.util.code.VerifyCode;
import com.cjst.util.common.CommonConstant;
import com.cjst.util.common.GenerativeToken;
import com.cjst.util.common.ResultCode;
import com.cjst.util.json.ResultObj;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.DefaultResult;
import cn.jpush.api.device.DeviceClient;

/**
 * APP登陆相关
 * @author yj
 *
 */
@Controller
@RequestMapping("/api")
public class LoginController extends BaseController{
	protected final Logger log = Logger.getLogger(LoginController.class);
	@Autowired
	private RedisService redisService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysMenuService sysMenuService;
	@Autowired
	private SysDictService dictService;
	@Autowired
	private SysUserService userService;
	@Autowired
	private SysOfficeService sysOfficeService;
	@Autowired
	private FileInfoService fileInfoService;
	@Autowired
	private ArticleService articleService;
	@Value("${file.path}")
	private String filePath;
	
	
	private DeviceClient deviceClient=JPushDeviceUtil.getInstance();
	/**
	 * 获取验证码
	 * @param imei
	 * @return
	 */
	@RequestMapping(value="/getCode",method = RequestMethod.POST)
	@ResponseBody
	public String getCode(){
		try {
			String code=VerifyCode.generateTextCode(0, 4, null);
			//生成codekey
			String codeKey=GenerativeToken.getToken();
			HashMap<String, String> map=new HashMap<String, String>();
			map.put("code", code);
			map.put("codeKey", codeKey);
			redisService.setObjByTime(CommonConstant.VERIFY_CODE+codeKey, code, 300);           //存验证码5分钟
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",map);
			return robj.toString();
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常",null);
			return robj.toString();
		}
	}
	/**
	 * 登陆过期，重新获取验证码
	 * @return
	 */
	@RequestMapping(value="/getCodeAge",method = RequestMethod.GET)
	@ResponseBody
	public String getCodeAges(){
		try {
			//String code=VerifyCode.generateTextCode(0, 4, null);
			//生成codekey
			//String codeKey=GenerativeToken.getToken();
			//HashMap<String, String> map=new HashMap<String, String>();
			//map.put("code", code);
			//map.put("codeKey", codeKey);
			//redisService.setObjByTime(CommonConstant.VERIFY_CODE+codeKey, code, 180);			//存验证码5分钟
			ResultObj robj = new ResultObj(ResultCode.RESULT_PARAM_ERROR, "登陆过期",null);
			return robj.toString();
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常",null);
			return robj.toString();
		}
	}
	/**
	 * 登陆
	 * @param userName
	 * @param passWord
	 * @param code
	 * @param codeKey
	 * @return
	 * @throws Exception
	 * 
	 * 
	 */
	
	//应安卓要求更改userName为account
	@RequestMapping(value="/login",method = RequestMethod.POST)
	@ResponseBody
    public String login( String account,String passWord,String code,String codeKey)  {
		String userName=account;
		try {
			if(userName==null || userName.length()==0){
				ResultObj robj = new ResultObj(ResultCode.RESULT_NULL, "用户名不为空",null);
				return robj.toString();
			}
			if(passWord==null || passWord.length()==0){
				ResultObj robj = new ResultObj(ResultCode.RESULT_NULL, "密码不能为空",null);
				return robj.toString();
			}
			/*if(codeKey==null || codeKey.length()==0){
				ResultObj robj = new ResultObj(ResultCode.RESULT_PHONE_NOT_CODE, "验证码过期",null);
				return robj.toString();
			}
			Object codes=redisService.getObj(CommonConstant.VERIFY_CODE+codeKey);
			if(codes==null){
				ResultObj robj = new ResultObj(ResultCode.RESULT_PHONE_NOT_CODE, "验证码过期",null);
				return robj.toString();
			}
			if(code==null || code.length()==0){
				ResultObj robj = new ResultObj(ResultCode.RESULT_PHONE_NOT_CODE, "验证码过期",null);
				return robj.toString();
			}
			if(!codes.toString().equals(code)){
				ResultObj robj = new ResultObj(ResultCode.RESULT_PHONE_NOT_CODE, "验证码错误",null);
				return robj.toString();
			}*/
			userName=userName.trim();
			passWord=passWord.trim();
			WherePrams wheres=Method.where("userName", C.EQ, userName);
			wheres.and("status", C.EQ, "1");
			List<SysUser> sysUserList=sysUserService.list(wheres);
			if(sysUserList==null || sysUserList.size()==0){
				log.info("=============客户端平台账号不存在");
				ResultObj robj = new ResultObj(ResultCode.RESULT_NULL, "账号不存在,请联系管理员",null);
				return robj.toString();
			}
			if(sysUserList.size()>1){
				log.info("=============客户端平台账号异常");
				ResultObj robj = new ResultObj(ResultCode.RESULT_NULL, "账号异常,请联系管理员",null);
				return robj.toString();
			}
			SysUser sysUser=sysUserList.get(0);
			String md5password = ShiroKit.md5(passWord, sysUser.getSalt());
			//String md5password = MethodUtil.getMD5(passWord, "UTF-8", 0);
			if(!md5password.equals(sysUser.getPassword())){
				log.info("=============客户端平台密码错误");
				ResultObj robj = new ResultObj(ResultCode.RESULT_NULL, "客户端平台密码错误,请重新输入",null);
				return robj.toString();
			}
			String token=GenerativeToken.getToken();
			String jsonString = JSONObject.toJSONString(sysUserList.get(0));
			JSONObject userJson = JSONObject.parseObject(jsonString);
			redisService.setObjByTime(CommonConstant.BUS_DICTIONARY_PREFIX+token, userJson, 604800);
			SysUser user=sysUserList.get(0);
			
			HashMap<String, Object> map=new HashMap<String, Object>();
			map.put("userId", user.getId());
			map.put("userName", user.getUserName());
			map.put("roleId", user.getRoleId());
			map.put("deptId", user.getDeptId());
			map.put("officeId", user.getOfficeId());
			map.put("token", token);
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",map);
			return robj.toString();
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常",null);
			return robj.toString();
		}
	}
	/**
	 * 获取到前端权限
	 * @param userId
	 * @return
	 */
	@RequestMapping(value="/getTopContent",method = RequestMethod.POST)
	@ResponseBody
	@Transactional	
	public String getTopContent(String userId,String userName){
		
		//String begin_url="http://192.168.0.159:8086/static/imgWork";
		String begin_url=filePath; 
		try {
			HashMap<String, Object> map=new HashMap<String, Object>();
			SysUser sysUser=sysUserService.get(userId);
			List<MenuNode> munuList=sysMenuService.menuRight(sysUser,1,1);
			List<MenuNode> fmunuList=new ArrayList<MenuNode>();					//功能型
			List<MenuNode> dataMunuList=new ArrayList<MenuNode>();					//数据型
			int fflag=0;
			int dataFlag=0;
			if(munuList!=null && munuList.size()>0){
				for (MenuNode menuNode : munuList) {
					if(menuNode.getIcon()!=null && menuNode.getIcon().length()>0){
						menuNode.setIcon(begin_url+menuNode.getIcon());
					}
					if(menuNode.getMenuType().equals(1)){			//功能型菜单
						if(fflag<7){
							
							fmunuList.add(menuNode);
							fflag++;
						}
					}else if(menuNode.getMenuType().equals(0)){			//数据型菜单
						if(dataFlag<4){
							/*
							 * 临时数值
							 */
							Random r = new Random();
							menuNode.setData(String.valueOf(r.nextInt(9)+r.nextInt(9)));
							/*
							 * 
							 */
							dataMunuList.add(menuNode);
							dataFlag++;
						}
					}
				}
			}
			
			map.put("fmunuList", fmunuList);
			map.put("dataMunuList", dataMunuList);
			/*
			List<FileInfo> fileList=fileInfoService.getFileInfo(1);					//获取APP banner图
			
			fileList.forEach(tmp->{
				tmp.setUrl(begin_url+tmp.getUrl());
			});
			
			map.put("fileList", fileList);					//banner图
			List<Article> tzList=articleService.getArticleByType(0);			//通知
			
			tzList.forEach(tmp->{
				tmp.setContent(null);
				
			});
			
			
			
			
			List<Article> lrList=articleService.getArticleByType(1);				//内容
			lrList.forEach(tmp->{
				tmp.setContent(null);
				
			});
			map.put("tzList", tzList);
			
			*/
			map.put("isAlarm", 0);					//是否有报警   0否  1是 
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",map);
			return robj.toString();
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "",null);
			return robj.toString();
		}
	}
	@RequestMapping(value="/getAllMenu",method = RequestMethod.POST)
	@ResponseBody
	public String getAllMenu(String userId,Integer menuType){
		try {
			if(menuType==null) {
				menuType=0;
			}
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",sysMenuService.getAllMenuByNode(userId,menuType));
			return robj.toString();
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常",null);
			return robj.toString();
		}
	}
	
	
	
	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	@ResponseBody
	public String logout(String registrationId) {
		DefaultResult defaultResult = unbind(registrationId);
		ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", defaultResult);
		return obj.toString();
	}

	public DefaultResult bind(String registrationId, String userId,String roleId) {
		
		DefaultResult result=null;
		
		Set<String> tagsToAdd=new HashSet<String>();
		tagsToAdd.add(roleId);
		
		Set<String> tagsToRemove=null;
		 try {
			 result=deviceClient.updateDeviceTagAlias(registrationId, userId, tagsToAdd,
			 tagsToRemove);
		} catch (APIConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (APIRequestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	public DefaultResult unbind(String registrationId) {
		DefaultResult defaultResult = null;
		try {
			deviceClient.updateDeviceTagAlias(registrationId, true, true);
		} catch (APIConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (APIRequestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// ResultObj obj=new
		// ResultObj(ResultCode.RESULT_SUCCESS,"success",defaultResult);
		return defaultResult;
	}
	
	
	
	@RequestMapping(value="/getWX_APPLET_TopContent",method = RequestMethod.POST)
	@ResponseBody
	public String getWX_APPLET_TopContent(){
		
		//String begin_url="http://192.168.0.159:8086/static/imgWork";
		String begin_url=filePath; 
		try {
			HashMap<String, Object> map=new HashMap<String, Object>();
			
			List<FileInfo> fileList=fileInfoService.getFileInfo(1);					//获取APP banner图
			
			fileList.forEach(tmp->{
				tmp.setUrl(begin_url+tmp.getUrl());
			});
			
			map.put("fileList", fileList);					//banner图
			List<Article> tzList=articleService.getArticleByType(0);			//通知
			
			tzList.forEach(tmp->{
				tmp.setContent(null);
				
			});
			
			
			
			
			List<Article> lrList=articleService.getArticleByType(1);				//内容
			lrList.forEach(tmp->{
				tmp.setContent(null);
				
			});
			map.put("tzList", tzList);
			
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",map);
			return robj.toString();
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "",null);
			return robj.toString();
		}
	}
}











